import 'package:get/get.dart';

import '../../data/models/user_model.dart';
import '../../data/repositories/user_repository.dart';
import '../../../core/base/base_service.dart';

/// 用户业务服务
/// 封装用户数据相关的核心业务逻辑
class UserBusiness {
  // 注入用户仓库
  final UserRepository _userRepository = Get.find<UserRepository>();
  
  /// 获取当前登录用户信息
  Future<UserModel?> fetchCurrentUserInfo() async {
    try {
      // 调用仓库获取用户信息
      final user = await _userRepository.getCurrentUser();
      
      // 可以在这里处理用户信息，例如根据角色进行一些初始化设置
      // if (user?.role == UserRole.admin) { ... }
      
      return user;
    } catch (e) {
      print('UserBusiness - Fetch current user failed: $e');
      // 可以根据需要返回默认值或重新抛出特定业务异常
      return null; 
    }
  }
  
  /// 更新用户个人资料
  /// 
  /// [userId] 要更新的用户ID
  /// [name] 新的用户名 (可选)
  /// [bio] 新的个人简介 (可选)
  /// [avatarUrl] 新的头像URL (可选)
  Future<UserModel> updateProfile(
    String userId, {
    String? name,
    String? bio,
    String? avatarUrl,
  }) async {
    // 构造需要更新的数据 Map
    final updateData = <String, dynamic>{};
    if (name != null) updateData['name'] = name;
    if (bio != null) updateData['bio'] = bio;
    if (avatarUrl != null) updateData['avatarUrl'] = avatarUrl;

    if (updateData.isEmpty) {
      // 如果没有提供任何要更新的数据，可以提前返回或抛出异常
      // 这里选择直接返回当前用户信息（如果能获取到）
      final currentUser = await _userRepository.getCurrentUser();
      if (currentUser != null && currentUser.id == userId) {
        return currentUser;
      }
      throw Exception('没有提供需要更新的信息');
    }

    try {
      // 调用仓库更新用户信息
      final updatedUser = await _userRepository.updateUserProfile(userId, updateData);
      return updatedUser;
    } catch (e) {
      print('UserBusiness - Update profile failed: $e');
      rethrow;
    }
  }
  
  /// 获取用户列表 (通常用于管理员)
  Future<List<UserModel>> fetchUserList({int page = 1, int limit = 10}) async {
    try {
      return await _userRepository.getUserList(page: page, limit: limit);
    } catch (e) {
      print('UserBusiness - Fetch user list failed: $e');
      return []; // 出错时返回空列表
    }
  }
  
  /// 根据 ID 获取特定用户信息 (通常用于管理员)
  Future<UserModel?> fetchUserById(String userId) async {
    try {
      return await _userRepository.getUserById(userId);
    } catch (e) {
      print('UserBusiness - Fetch user by ID failed: $e');
      return null;
    }
  }
  
  /// 获取当前用户信息
  Future<UserModel?> getCurrentUser() async {
    return await handleError<UserModel?>(() async {
      return await _userRepository.getCurrentUser();
    });
  }
  
  /// 更新用户信息
  Future<UserModel?> updateProfile({
    required String userId,
    String? displayName,
    String? email,
    String? phone,
    String? avatarUrl,
    String? bio,
    String? address,
    String? city,
    String? country,
    String? zipCode,
    Map<String, dynamic>? extraData,
  }) async {
    return await handleError<UserModel?>(() async {
      return await _userRepository.updateProfile(
        userId: userId,
        displayName: displayName,
        email: email,
        phone: phone,
        avatarUrl: avatarUrl,
        bio: bio,
        address: address,
        city: city,
        country: country,
        zipCode: zipCode,
        extraData: extraData,
      );
    });
  }
  
  /// 更改密码
  Future<bool> changePassword({
    required String oldPassword,
    required String newPassword,
  }) async {
    return await handleError<bool>(() async {
      return await _userRepository.changePassword(
        oldPassword: oldPassword,
        newPassword: newPassword,
      );
    });
  }
  
  /// 获取用户列表
  Future<List<UserModel>> getUserList({
    Map<String, dynamic>? filters,
  }) async {
    return await handleError<List<UserModel>>(() async {
      return await _userRepository.getUserList(
        filters: filters,
      );
    });
  }
  
  /// 获取用户详情
  Future<UserModel?> getUserDetail({
    required String userId,
  }) async {
    return await handleError<UserModel?>(() async {
      return await _userRepository.getUserDetail(
        userId: userId,
      );
    });
  }
  
  /// 删除用户
  Future<bool> deleteUser({
    required String userId,
  }) async {
    return await handleError<bool>(() async {
      return await _userRepository.deleteUser(
        userId: userId,
      );
    });
  }
  
  /// 激活/停用用户
  Future<UserModel?> toggleUserActive({
    required String userId,
    required bool isActive,
  }) async {
    return await handleError<UserModel?>(() async {
      return await _userRepository.toggleUserActive(
        userId: userId,
        isActive: isActive,
      );
    });
  }
  
  /// 更新用户角色
  Future<UserModel?> updateUserRole({
    required String userId,
    required String role,
  }) async {
    return await handleError<UserModel?>(() async {
      return await _userRepository.updateUserRole(
        userId: userId,
        role: role,
      );
    });
  }
  
  /// 检查用户是否为管理员
  bool isAdmin(UserModel user) {
    return user.role.toLowerCase() == 'admin';
  }
  
  /// 获取用户完整姓名
  String getFullName(UserModel user) {
    return user.displayName ?? user.username;
  }
  
  /// 获取用户地址
  String getFullAddress(UserModel user) {
    final List<String> addressParts = [];
    
    if (user.address != null && user.address!.isNotEmpty) {
      addressParts.add(user.address!);
    }
    
    if (user.city != null && user.city!.isNotEmpty) {
      addressParts.add(user.city!);
    }
    
    if (user.country != null && user.country!.isNotEmpty) {
      addressParts.add(user.country!);
    }
    
    if (user.zipCode != null && user.zipCode!.isNotEmpty) {
      addressParts.add(user.zipCode!);
    }
    
    return addressParts.join(', ');
  }
} 